package lesson02;

import java.io.IOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class UDPEchoServer03 {
    private DatagramSocket socket;

    public UDPEchoServer03(int port) throws SocketException {
        if (port < 1024 || port > 65535) {
            throw new BindException("端口号需选择 1024 - 65535 区间");
        }
        socket = new DatagramSocket(port);  //这里自动分配的ip是谁的？？
    }

    public void start() throws IOException {
        System.out.println("服务器启动.");
        while (true) {
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength(), "UTF-8");
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),
                    0, response.getBytes().length, requestPacket.getSocketAddress());//这里接收的ip是谁的？？
            socket.send(responsePacket);
            System.out.printf("[%s:%d] request = %s response = %s\n", requestPacket.getAddress().toString(),
                    requestPacket.getPort(), request, response);
        }
    }

    private String process(String request) {
        return request;
    }


    public static void main(String[] args) throws IOException {
        UDPEchoServer03 udpEchoServer03 = new UDPEchoServer03(9999);
        udpEchoServer03.start();
    }

}



